from celery.task import task
from util.requestOwn import my_request
from uuid import uuid4
import os
import json

from apps.delay_missions.active_task import ActiveTask
from django.conf import settings
from .models import Gateway, Sensor
from apps.missions.models import Mission


# 8: "上传配置文件",
@task(name="active_task")
def active_task(data):
    mission_id = data.get("mission_id")
    mission = Mission.objects.filter(id=mission_id).first()
    gateway = Gateway.objects.filter(key=mission.key).first()
    data = {}
    file_path = "".join([settings.DEPLOY_JSON_FILE_DIR, "/", str(gateway.gateway_id), ".json"])
    data["file_path"] = file_path
    data["mission"] = mission
    data["gateway_id"] = gateway.gateway_id
    data["gateway_client_id"] = gateway.client_id
    gateway.active_state = 0
    gateway.save()
    my_request.remove_file(file_path)
    activeTask = ActiveTask(data)
    activeTask.run()
    result = my_request.is_file_exit(file_path)
    if result:
        md5 = mission.mission_result
        result = my_request.get_md5(file_path, "0")
        md5_2 = result.get("md5")
        if md5 == md5_2:
            gateway.active_state = 1
            gateway.save()
            mission.state = 1
            mission.save()
            content = my_request.ana_file(file_path)
            if content:
                sensor_ids = content.get("sensor_ids")
                if sensor_ids:
                    add_sensor(gateway.key, sensor_ids)
        else:
            mission.state = -1
            mission.failed_reason = "文件不完全"
            mission.save()
            gateway.active_state = -1
            gateway.save()
    else:
        if not mission.state == -1:
            mission.state = -1
            mission.failed_reason = "无文件上传"
            mission.save()
        gateway.active_state = -1
        gateway.save()


def add_sensor(key, sensor_ids):
    Sensor.delete_sensors(key)
    sensors = []
    for sensor_id in sensor_ids:
        sensors.append(Sensor(id=str(uuid4()).replace("-", ""), number=sensor_id, gateway_id=key))
    Sensor.objects.bulk_create(sensors)

